package com.example.demo.service;

import com.example.demo.dao.BookMapper;
import com.example.demo.entity.Book;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;


@Service
public class BookService {
    @Autowired
    BookMapper bookMapper;

    //测试使用，id查所有
    public Book selectBookById(String book_id) {
        return bookMapper.selectBookById(book_id);
    }

    public String postBook(String book_name, String book_author, String book_publisher, String book_type, String book_price,
                           String book_degree, String book_description, String book_image, String seller_id) {
        Timestamp post_time = new Timestamp(System.currentTimeMillis());
        String book_id = post_time.getTime() + "_" + seller_id;//生成一个唯一id
        String book_status = "ON_SALE";
        BigDecimal decimal_price = new BigDecimal(book_price);
        bookMapper.insertBook(book_id, book_name, book_author, book_publisher, book_type, decimal_price,
                book_degree, book_description, book_image, seller_id, book_status, post_time);
        return book_id;
    }

    public ArrayList<Book> selectBookByInfo(String book_name, String book_type, String order_type) {
        return bookMapper.selectBookByInfo(book_name, book_type, order_type);
    }

    public int tradeBook(String book_id, String buyer_id) {
        Book book = bookMapper.selectBookById(book_id);
        if (!book.getBook_status().equals("ON_SALE"))
            return -1;
        Timestamp trade_time = new Timestamp(System.currentTimeMillis());
        String book_status = "TRADING";
        bookMapper.updateBook(book_id, null, null, null, null, null,
                null, null, null, null, buyer_id,
                book_status, null, trade_time, null);
        return 0;
    }

    public int accomplishTrade(String book_id) {
        Book book = bookMapper.selectBookById(book_id);
        if (!book.getBook_status().equals("TRADING"))
            return -1;
        Timestamp accomplish_time = new Timestamp(System.currentTimeMillis());
        String book_status = "ACCOMPLISHED";
        bookMapper.updateBook(book_id, null, null, null, null, null,
                null, null, null, null, null,
                book_status, null, null, accomplish_time);
        return 0;
    }

    public ArrayList<Book> selectBookByUser(String user_id, String select_type) {
        return bookMapper.selectBookByUser(user_id, select_type);
    }
}
